﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace tablegen2.logic
{
    public class TableExcelExportTxt
    {

       // public static void appendFormatLineEx(StringBuilder sb, int indent, string fmtstr, params object[] args)
       // {
       //     if (indent > 0)
       //         sb.Append(new String('\t', indent));
       //         //sb.Append(new String('\t', indent * 4));
       //
       //     sb.AppendFormat(fmtstr, args);
       //     sb.AppendLine();
       // }
        public static void appendFormatLine(StringBuilder sb, int indent, string fmtstr)
        {

      
                if (string.IsNullOrWhiteSpace(fmtstr.Trim()))
                {
                    fmtstr = Regex.Replace(string.Empty, @"\s", "");
                }
                else
                {
                    fmtstr = Regex.Replace(fmtstr, @"\s", "");
                }
                fmtstr = Regex.Replace(fmtstr, @"\t", "");
            
               // sb.Append(new String('\t', indent));
            //sb.Append(new String('\t', indent * 4));
          
            sb.Append(fmtstr);
            //sb.AppendLine();

        }

        public static void appendFormatLine(StringBuilder sb,string fmtstr)
        {

            if (string.IsNullOrWhiteSpace(fmtstr))
            {
                sb.Append(Regex.Replace(string.Empty, @"\s", ""));
     
            }
            else
            {
                sb.Append(Regex.Replace(fmtstr, @"\s", ""));
            }
        
            sb.Append("\t");
     
       

        }

        public static void appendLine(StringBuilder sb, bool line = true)
        {
            if (line)
                sb.AppendLine();

        }



        public static void exportExcelFile(TableExcelData data, string filePath)
        {
            var sb = new StringBuilder();

            var ids = new List<string>();
           // var keys = new List<string>();

            List<TableExcelHeader> propertys = data.Headers;

            #region 表头

            for (int i = 0; i < propertys.Count; i++)
            {             
                appendFormatLine(sb ,propertys[i].FieldName);
            }


            appendLine(sb);

            #endregion
            
            foreach (var row in data.Rows)
            {

                if (string.IsNullOrEmpty(row.StrList[0]))
                    continue;

                for (int i = 0; i < data.Headers.Count; i++)
                {
                

                    //appendFormatLine(sb, i != 0 ? 1 : i, row.StrList[i]);
                    appendFormatLine(sb, row.StrList[i]);
 
                  
                }
                appendLine(sb);
            }


            File.WriteAllBytes(filePath, Encoding.UTF8.GetBytes(sb.ToString()));
        }


    }
    
}
